package br.com.mundodaprata.store.data.gen;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import br.com.mundodaprata.store.data.jdbc.CityRepositoryJDBC;
import br.com.mundodaprata.store.model.City;
import br.com.mundodaprata.store.model.TypeCity;


public class CityGen implements DataGen {
   
	@Override
	public void gen() throws Exception {
		List<City> cities = new ArrayList<City>();
		
		File file = new File("C:\\java\\cities.txt");
		FileReader fr = new FileReader(file);
		BufferedReader reader = new BufferedReader(fr);
		
		String line;
		
		while((line=reader.readLine())!=null){
			String[] data = line.split(";");
			
			City city = new City();
			city.setCode(Long.parseLong(data[0]));
			city.setState(data[1]);
			city.setName(data[2]);
			city.setZipCode(data[3]);
			city.setTypeCity(TypeCity.valueOf(data[4]));
			
			if(data.length==6){
				City major = new City();
				major.setCode(Long.parseLong(data[5]));
				city.setMajor(major);
			}
			
			cities.add(city);
		}
		
		Collections.sort(cities, new Comparator<City>() {
			@Override
			public int compare(City o1, City o2) {
				Integer ordinal1 = o1.getTypeCity().ordinal();
				Integer ordinal2 = o2.getTypeCity().ordinal();
				
				return ordinal1.compareTo(ordinal2);
			}
		});
		
		Iterator<City> iterator = cities.iterator();
		
		while(iterator.hasNext()){
			City city = iterator.next();
			
			if(city.getMajor()==null){
				continue;
			}
			
			if(!cities.contains(city.getMajor())){
				iterator.remove();
			}
		}
		
		CityRepositoryJDBC jdbc = new CityRepositoryJDBC();
		jdbc.insert((City[]) cities.toArray(
				new City[cities.size()]));
		jdbc.closeConnection();
	}
}